<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Repository\Repositories\Interfaces\PermissionRepository;

/**
 * 权限管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class PermissionController extends BaseController
{
    private  $permissionRepository;
    
    public function __construct(PermissionRepository $permissionRepository,Request $request)
    {
        parent::__construct();
        $this->request = $request;
        $this->permissionRepository = $permissionRepository;
        
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $type = $this->request->only(['type']);
        $type = isset($type['type'])?$type['type']:'page';
        if ($type=='all'){
            $ret = $this->permissionRepository->all();
            $data = $ret['data'];
//            dd($data);
        }else{
            $ret = $this->permissionRepository->orderBy('id','desc')->paginate($this->perPage);
            $data = ['list' => $ret['data'],'page' => $ret['meta']['pagination']];
        }
        return $this->success('ok',$data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\Form\PermissionCreateForm $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'name'         => 'required',
            'display_name' => 'required',
            'description'  => 'required',
        ],[
            'name.required'         => '权限标识不能为空',
            'display_name.required' => '权限名称不能为空',
            'description.required'  => '权限描述不能为空',
        ]);
        try {
            if ($role = $this->permissionRepository->create($request->only(['name','display_name','description']))) {
                return $this->success('创建权限成功',$role['data']);
            }
        }
        catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $ret = $this->permissionRepository->find($id);
        return $this->success('ok', $ret['data']);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'         => 'required',
            'display_name' => 'required',
            'description'  => 'required',
        ],[
            'name.required'         => '权限标识不能为空',
            'display_name.required' => '权限名称不能为空',
            'description.required'  => '权限描述不能为空',
        ]);
        try {
            if ($role = $this->permissionRepository->update($request->all(),$id)) {
                return $this->success("编辑权限成功",$role['data']);
            }
        }
        catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            if ($this->permissionRepository->delete($id)) {
                return $this->success("删除权限成功");
            }
        }
        catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 关联权限页面
     *
     * @param $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function associate($id)
    {
        $permission = $this->permissionRepository->skipPresenter(1)->find($id);
        switch ($permission->type) {
            case 'menu':
                $data = $this->permissionRepository->getAllMenusTreeByPermissionModel($permission);
                foreach ($data as $key => $item) {
                    $data[$key]['name'] = trans($item['name']);
                }
                $data = json_encode($data);
                break;
            case 'action':
                $data = json_encode($this->permissionRepository->getAllActionsByPermissionModel($permission));
                break;

        }

        return view('backend.permission.' . $permission->type, compact('data', 'id'));
    }

    /**
     * 关联菜单权限操作
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function associateMenus(Request $request)
    {
        $id = $request['id'];
        $menus = $request['menus'];

        try {
            $permission = PermissionRepository::find($id);

            if ($permission->menus()->sync($menus ? $menus : [])) {
                event(new ClearUserPermissionCacheEvent());

                return $this->responseJson(['status' => 1, 'message' => '关联菜单权限成功']);
            } else {
                return $this->responseJson(['status' => 0, 'message' => '关联菜单权限失败']);
            }
        }
        catch (\Exception $e) {
            return $this->responseJson(['status' => 0]);
        }
    }

    /**
     * 关联操作权限操作
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function associateActions(Request $request)
    {
        $id = $request['id'];
        $actions = $request['actions'];

        try {
            $permission = PermissionRepository::find($id);

            if ($permission->actions()->sync($actions)) {
                event(new ClearUserPermissionCacheEvent());

                return $this->responseJson(['status' => 1, 'message' => '关联操作权限成功']);
            } else {
                return $this->responseJson(['status' => 0, 'message' => '关联操作权限失败']);
            }
        }
        catch (\Exception $e) {
            return $this->responseJson(['status' => 0]);
        }
    }
}
